package cn.itcast.controller;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;

    @RequestMapping(value = "/login", name = "登录用户")
    public String login(String email, String password) {
        /*if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            request.setAttribute("error", "用户和密码不能为空");
            return "forward:login.jsp";
        }

        User user = userService.findByEmail(email);
        if (user == null) {
            request.setAttribute("error", "用户名不存在");
            return "forward:login.jsp";
        } else {
            password = new Md5Hash(password, email, 2).toString();
            if (!password.equals(user.getPassword())) {
                request.setAttribute("error", "密码输入有误");
                return "forward:login.jsp";
            }
            List<Module> moduleList = moduleService.findModulesByUser(user);
            session.setAttribute("modules", moduleList);
        }*/

        // 使用shrio框架重写登录方法
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            request.setAttribute("error","邮箱或密码不能为空");
            return "forward:login.jsp";
        }
        password = new Md5Hash(password, email, 2).toString();
        // 创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        // 获取主题
        Subject subject = SecurityUtils.getSubject();
        // 开始认证
        try {
            subject.login(token);
        }catch (AuthenticationException e){
            request.setAttribute("error","邮箱或密码错误");
            return "forward:login.jsp";
        }
        User user = (User) subject.getPrincipal();
        session.setAttribute("loginUser", user);
        List<Module> moduleList = moduleService.findModulesByUser(user);
        session.setAttribute("modules", moduleList);
        return "home/main";
    }

    @RequestMapping(value = "/logout", name = "退出登录")
    public String logout() {
//        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home() {
        return "home/home";
    }

}
